package org.kev.transit;

import java.util.ArrayList;

import org.kev.transit.data.TimeTable;
import org.kev.transit.util.TransitConst;
import org.kev.transit.util.TransitUtil;
import org.kev.transit.worker.DataWorker;


import android.content.Intent;
import android.content.SharedPreferences;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
/** 
 * This shows time table information for the given mode of mass transit.  The data displayed is based on a Web service(JSON) call that is then cached in
 * the local DB.  Someday it will also expire cached data in the DB.  All DB updates 
 * occur in a background thread.
 * @author kevin
 *
 */
public class TimeTableActivity extends DataActivity{
	 
	   // static final private int NEXT_ID = FIRST_MENU + 2;
		private static final String TAG =  "org.kev.transit.TimeTableActivity";
		private ArrayAdapter <TimeTable> arrayAdaptor= null;
		private static final DataWorker mWorker=new DataWorker();
		private static Handler mHandler = null;

	    private ListView mTimeTableList;
	   
		
	    
	    public TimeTableActivity() {
	    	if(mHandler==null){
	    		mHandler=new Handler();
	    	}
	    }

	    /** Called with the activity is first created. */
	    @Override
	    public void onCreate(Bundle icicle) {
	        super.onCreate(icicle);

	        requestWindowFeature(Window.FEATURE_PROGRESS);
   	       
//	        setProgress(5000);
	        // Inflate our UI from its XML layout description.
	        setContentView(R.layout.time_table);
	        setProgressBarVisibility(true);
	        setProgressBarIndeterminate(true);
	        //setContentView(R.layout.screen_simple);

	        mTimeTableList = (ListView) findViewById(R.id.timeTableList);
			mWorker.init(this,mHandler,mUpdateResults);
			Thread t = new Thread(mWorker);
			t.setDaemon(true);
			t.start();
			mTimeTableList.setOnItemSelectedListener(mTimeTableListener );
//			mTimeTableList.setOnItemClickListener(mItemListener);
	        // Hook up button presses to the appropriate event handler.
	        //((Button) findViewById(R.id.back)).setOnClickListener(mBackListener);  
	        

	    }

	    /**
	     * Called when the activity is about to start interacting with the user.
	     */
	    @Override
	    protected void onResume() {
	        super.onResume();
	        setProgressBarVisibility(true);
	        mWorker.init(this,mHandler,mUpdateResults);
			Thread t = new Thread(mWorker);
			t.setDaemon(true);
			t.start();

			Log.d(TransitConst.TAG,".onResume restore Prefs !");
			
	    }
	    
	    /**
	     * 
	     */
		private void timeTableSelected(){
			Log.d(TransitConst.TAG,"time selected");
			
			mTimeTableList.getSelectedItem();
			if( mTimeTableList.getSelectedItem()!=null){
				String temp =mTimeTableList.getSelectedItem().toString();
				TransitConf.currentTime=temp;
			}
			
		}
	    /**
		 * set the currently select direction item based on pref if it exist
		 * @param stopList
		 */
		private void setCurrentTimeTable(ListView stopList) {
		
		       SharedPreferences settings = getSharedPreferences(TransitConst.PREFS_NAME, 0);
			   String current = settings.getString(TransitConst.TIME_PREF,"none");
			   Log.d(TAG,"current time pref="+current);
			  ListAdapter stop= stopList.getAdapter();
			   int count =stopList.getCount();
			   for (int i=0;i<count;i++){
				   String s =stop.getItem(i).toString();
//				   Log.d(TransitConst.TAG,"current pref="+current);
				   if (s!=null && s.equals(current) ){
					   Log.d(TransitConst.TAG,"found slection"+s);
					   stopList.setSelection(i);
					   return;
				   }
			   }
		}
		/**
		 * 
		 * I am being paused save all prefs
		 */
			@Override
			protected void onPause() {
				super.onPause();
				Log.d(TAG,"onPAUSE Save Prefs!");
				Log.d(TAG,TransitConf.toXML() );
				TransitUtil.savePref(this,TransitConst.TIME_PREF,TransitConf.currentTime);
			}

	    /**
	     * Called to remember the current state before the activity stops.
	     */
	    @Override
	    protected void onFreeze(Bundle outState) {
	        super.onFreeze(outState);

	        // Save the current text editor state. As noted above in
	        // onCreate(), this is somewhat unusual in that our text
	        // is not in persistent storage. If we did have it in persistent
	        // storage, we would call mEditor.saveState() here instead.
	        //outState.putBundle("text", mEditor.saveStateAndText());
	    }

	    /**
	     * Called when your activity's options menu needs to be created.
	     */
	    @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        super.onCreateOptionsMenu(menu);

	
	        return true;
	    }

	    /**
	     * Called right before your activity's option menu is displayed.
	     */
	    @Override
	    public boolean onPrepareOptionsMenu(Menu menu) {
	        super.onPrepareOptionsMenu(menu);

	        // Before showing the menu, we need to decide whether the clear
	        // item is enabled depending on whether there is text to clear.
	 //       menu.setItemShown(CLEAR_ID, mEditor.getText().length() > 0);

	        return true;
	    }

	    /**
	     * Called when a menu item is selected.
	     */
	    @Override
	    public boolean onOptionsItemSelected(Menu.Item item) {
	        //switch (item.getId()) {


	        return super.onOptionsItemSelected(item);
	    }
	    /**
	     * 
	     */
		public void nextScreen() {
			//no more screens maybe I should display some sort 
			//of detail summary screen
			
		}
		/**
		 * populate an array adapter with data this is called by a worker thread
		 */
		public void setData(){
			Log.d(TAG,">>> setData");
			try{

				Uri curi  = TimeTable.CONTENT_URI;
				Intent i = new Intent();
				i.setData(curi);
				setIntent(i);
				String dirId =TransitConf.currentDirectionId;
				String routeId =TransitConf.currentRouteId;
				String routeTypeId =TransitConf.currentRouteTypeId;
				String stop =TransitConf.currentStopId;
	     		ArrayList <TimeTable> list = TimeTable.getData(this, dirId, routeId, routeTypeId, stop);
				arrayAdaptor = new  ArrayAdapter <TimeTable> (this,android.R.layout.simple_list_item_1,list);
		
			}catch(Exception e){
				Log.e(TAG,"setStopData()",e);
			}
			Log.d(TAG,"<<< setData");
		}
	    /************INNER classes*******************************************/
	    /**
	     *  Create runnable for posting UI updates
	     */
	   Runnable mUpdateResults = new Runnable() {

	    	public void run() {
	    		Log.d(TAG,"set mUpdateResults.run()="+arrayAdaptor);
	    		mTimeTableList.setAdapter(arrayAdaptor);
	    		setCurrentTimeTable(mTimeTableList);
	    		setProgressBarVisibility(false);	        }
	    };
		/**
		 * A call-back for click on a selected item
		 */
	    OnItemClickListener mItemListener = new OnItemClickListener() {

			public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
				nextScreen();				
			}
		};	    
		/**
		 * A call-back for when select a Time from list
		 */
		OnItemSelectedListener  mTimeTableListener = new OnItemSelectedListener() {
			public void onItemSelected(AdapterView parent, View v, int position, long id){
				timeTableSelected();
			}
			public void onNothingSelected(AdapterView parent){
				
				Log.e(TAG,"Nothing selected!");
			}
		};
	    /**
	     * A call-back for when the user presses the back button.
	     */
	    OnClickListener mBackListener = new OnClickListener() {
	        public void onClick(View v) {
	            finish();
	        }
	    };

	    /**
	     * A call-back for when the user presses the clear button.
	     */
	    OnClickListener mClearListener = new OnClickListener() {
	        public void onClick(View v) {
	         //   mEditor.setText("");
	        }
	    };


}
